﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Smart.Service
{
    public class XmlServiceRequest : IServiceRequest
    {
        public XmlServiceRequest()
        {
            Root = new XElement("request");
        }

        public XmlServiceRequest(XElement root)
        {
            Root = root;
        }

        public XElement Root { get; protected set; }

        public bool Contains(string key)
        {
            return Root.Element(key) != null;
        }

        public virtual string ToXmlString()
        {
            return Root.ToString();
        }

        public string this[string key]
        {
            get
            {
                if (Contains(key))
                    return Root.Element(key).Value;
                return string.Empty;
            }
            set
            {
                if (Contains(key))
                    Root.Element(key).SetValue(value);
                else
                    Root.Add(new XElement(key, value));
            }
        }


        public IServiceRequest Clone()
        {
            XmlServiceRequest request = new XmlServiceRequest();
            foreach (var x in Root.Elements())
            {
                request[x.Name.ToString()] = x.Value;
            }

            return request;
        }
    }
}
